import { FormItemConfig, ItemValidateResult } from '@/components/form-design/item-select/config/type';
import {
  CASCADER_CONFIG,
  CHECK_BOX_CONFIG,
  RADIO_CONFIG,
  SELECT_CONFIG,
  TREE_SELECT_CONFIG
} from '@/components/form-design/item-select/config/config';

/**
 * 校验选项
 * @param config
 */
const validateOption: (config: FormItemConfig) => boolean = function(config) {
  if (!config.config || !config.config.options) {
    return true;
  }
  const optionsLength = config.config.options.length;
  if (optionsLength <= 0) {
    return true;
  }
  for (let index = 0, l = config.config.options.length; index < l; index += 1) {
    const item = config.config.options[index];
    if (!item.value || !item.label) {
      return true;
    }
  }
  // @ts-ignore
  const labelSet = new Set(config.config.options.map(item => item.label));
  // @ts-ignore
  const valueSet = new Set(config.config.options.map(item => item.value));
  return labelSet.size < optionsLength || valueSet.size < optionsLength;
};

/**
 * 校验表单配置项
 * @param config
 * @return true 不通过  false 通过
 */
export const validateFormItemConfig: (config: FormItemConfig) => ItemValidateResult = function(config) {
  if (config.type === CHECK_BOX_CONFIG.type || config.type === RADIO_CONFIG.type || config.type === SELECT_CONFIG.type) {
    if (validateOption(config)) {
      return { status: true, message: `${config.name} ${config.id} 选项配置有误` };
    }
  }
  if (config.type === CASCADER_CONFIG.type || config.type === TREE_SELECT_CONFIG.type) {
    if (!config.config.options) {
      return { status: true, message: `${config.name} ${config.id} 选项数据` };
    }
  }
  return { status: false };
};